package com.angel.provider.app.impl;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.angel.core.Constants;
import com.angel.core.util.CodeUtil;
import com.angel.core.util.DateUtils;
import com.angel.core.util.JsonUtil;
import com.angel.dao.health.BuzAssessmentMapper;
import com.angel.dao.health.BuzMachineMapper;
import com.angel.health.BuzAssessment;
import com.angel.health.BuzCustomer;
import com.angel.health.BuzExaminationParsingWithBLOBs;
import com.angel.health.BuzMachine;
import com.angel.health.ln.WangYi;
import com.angel.provider.app.BuzMachineProvider;
import com.angel.provider.app.WangYiProvider;
import com.angel.provider.health.BuzCustomerProvider;
import com.angel.provider.health.BuzExaminationParsingProvider;
import com.github.pagehelper.StringUtil;

/**
 * @author 作者姓名 cheng
 * @version 创建时间：2016年10月11日 下午2:27:12 类说明 一体机解析数据
 */
@Service
public class BuzMachineProviderImpl implements BuzMachineProvider {

	@Autowired
	private BuzMachineMapper bmMapper;
	@Autowired
	private BuzCustomerProvider customerProvider;
	@Autowired
	private BuzExaminationParsingProvider bpProvider;
	@Autowired
	private BuzAssessmentMapper baMapper;
	@Autowired
	private WangYiProvider wyService;

	@Override
	public void readMachine(String result) {
		// TODO Auto-generated method stub
		Map<String, Object> map = JsonUtil.jsonToMap(result);
		BuzExaminationParsingWithBLOBs bepwb = new BuzExaminationParsingWithBLOBs();
		bepwb.setMachineId(map.get("machineId") == null ? "" : map.get("machineId").toString());
		bepwb.setMacAddr(map.get("macAddr") == null ? "" : map.get("macAddr").toString());

		String customer = map.get("member") == null ? "" : map.get("member").toString();
		BuzCustomer bc = new BuzCustomer();
		if (!StringUtil.isEmpty(customer)) {
			bc = setCustomer(customer);
		}
		List<Map<String, Object>> customerCount = customerProvider.findCustomerByPhone(bc);
		if (customerCount.size() > 0) {
			bc.setId(Integer.parseInt(customerCount.get(0).get("id").toString()));
		} else {
			String createUser = "";
			try {
				createUser = wyService.createUser(JsonUtil.toJson(new WangYi(bc.getMemPhone(), bc.getName())));
				if (!StringUtils.isEmpty(createUser)) {
					Map<String, String> tokenmap = JsonUtil.jsonStringToMap(createUser);
					if ("200".equals(tokenmap.get("code"))) {
						bc.setToken(tokenmap.get("token"));
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				bc.setToken("生成失败");
			}

			bc.setLabelId(1);
			bc.setMemberForm(0);
			customerProvider.insert(bc);
			bc.setCode(CodeUtil.createCode(null, Constants.CUSTOMERNUM, bc.getId()));
			customerProvider.updateById(bc);
		}

		List<BuzMachine> machineList = bmMapper.findAll(null);
		Map<String, BuzMachine> machineMap = findMachine(machineList);

		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		for (Entry<String, Object> entry : map.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();
			if ("macAddr".equals(key) || "machineId".equals(key) || "member".equals(key) || "recordNo".equals(key)) {
				continue;
			}
			BuzMachine bm = machineMap.get(key);
			Map<String, String> _resultMap = new LinkedHashMap<String, String>();
			Map<String, Object> _valueMap = JsonUtil.jsonToMap(value == null ? "" : value.toString());
			for (Entry<String, Object> _entry : _valueMap.entrySet()) {
				String _key = _entry.getKey();
				Object _value = _entry.getValue();
				BuzMachine bm2 = machineMap.get(_key + bm.getId());
				if (bm2 == null) {
					continue;
				}
				if (!StringUtil.isEmpty(bm2.getResult()) && _value != null && !"null".equals(_value.toString())) {
					_value = bm2.getResult().split(",")[Integer.parseInt(_value.toString()) - 1];
				}
				if (StringUtil.isEmpty(bm2.getName())) {
					continue;
				}
				_resultMap.put(bm2.getName(), _value == null ? "" : _value.toString());
			}
			resultMap.put(bm.getName(), _resultMap);
		}

		bepwb.setMedical(JsonUtil.toJson(resultMap));
		bepwb.setMachineValue(result);
		bepwb.setCustomerId(bc.getId());
		Object measureTime = ((Map) map.get("member")).get("measureTime");
		if (measureTime != null) {
			bepwb.setMedicalTime(DateUtils.getDateTime(measureTime.toString()));
		}
		bpProvider.insert(bepwb);

		BuzAssessment ba = new BuzAssessment();
		ba.setCustomerId(bc.getId());
		// List<Map<String, Object>> baList = baMapper.findAssessmentAll(ba);
		Date date = new Date();
		ba.setExaminationParsingId(bepwb.getId());
		// if(baList.size() > 0){
		// ba.setUpdateTime(date);
		// ba.setId(Integer.parseInt(baList.get(0).get("id").toString()));
		// baMapper.updateByPrimaryKeySelective(ba);
		// }else{
		ba.setUpdateTime(date);
		ba.setCreateTime(date);
		ba.setEnable(1);
		baMapper.insert(ba);
		ba.setCode(CodeUtil.createCode(null, Constants.ASSESSMENT, ba.getId()));
		baMapper.updateByPrimaryKeySelective(ba);
		// }
	}

	private Map<String, BuzMachine> findMachine(List<BuzMachine> machineList) {
		Map<String, BuzMachine> map = new LinkedHashMap<String, BuzMachine>();
		for (BuzMachine machine : machineList) {
			map.put(machine.getCode() + (machine.getParid() == null ? "" : machine.getParid()), machine);
		}
		return map;
	}

	/**
	 * 解析一体机客户基本信息部分
	 * 
	 * @param customer
	 * @return
	 */
	private BuzCustomer setCustomer(String customer) {
		Map<String, Object> map = JsonUtil.jsonToMap(customer);
		BuzCustomer bc = new BuzCustomer();
		bc.setNational(map.get("folk") == null ? "" : map.get("folk").toString());
		bc.setLssuedOffice(map.get("agency") == null ? "" : map.get("agency").toString());
		String cardValidDate = map.get("valid") == null ? "" : map.get("valid").toString();
		if (!"".equals(cardValidDate)) {
			bc.setCardValidDate(DateUtils.getDate(cardValidDate));
		}
		bc.setName(map.get("name") == null ? "" : map.get("name").toString());
		String memPhone = map.get("phone") == null ? "" : map.get("phone").toString();
		String idcard = map.get("idcard") == null ? "" : map.get("idcard").toString();
		bc.setCardNumber(idcard);
		if ("".equals(memPhone)) {
			bc.setMemPhone(idcard);
		} else {
			bc.setMemPhone(memPhone);
		}
		String sex = map.get("sex") == null ? "" : map.get("sex").toString();
		if ("男".equals(sex)) {
			bc.setSex(1);
		} else if ("女".equals(sex)) {
			bc.setSex(2);
		} else {
			bc.setSex(0);
		}
		bc.setDetailAddress(map.get("address") == null ? "" : map.get("address").toString());
		// bc.setPortraitUrl(map.get("userIcon")==null?"":map.get("userIcon").toString());
		bc.setBirthday(map.get("birthday") == null ? "" : map.get("birthday").toString());
		return bc;
	}
}
